package org.extreme.web.core.support;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.extreme.core.plugin.AbstractPlugin;
import org.extreme.web.core.action.ActionException;
import org.extreme.web.core.action.IAction;
import org.extreme.web.core.cfg.WebCfg;
import org.extreme.web.core.cfg.WebGlobal;
import org.extreme.web.core.env.Env;

public class WebPlugin extends AbstractPlugin{
	
	protected WebCfg webConfig;
	protected Class<? extends WebCfg> webConfigClass;
	protected transient ServletContext context;
	
	public WebPlugin(Class<? extends WebCfg> webConfigClass){
		this.webConfigClass = webConfigClass;
	}
	
	@Override
	public void init(ServletConfig config) {
		webConfig = loadConfig(webConfigClass);
        context = config.getServletContext();
	}

	@Override
	public void before(HttpServletRequest req, HttpServletResponse resp) {
	}

	@Override
	public void service(HttpServletRequest req, HttpServletResponse resp) {
        Env.create(req, resp, context);//创建环境
        try{
	        IAction action = WebGlobal.getResolver().resolvePath();//解析action
	        if(action==null){
	        	WebGlobal.getDefaultRender().render404();
	        }else{
	        	action.getInvoker().invoke();//执行action
	        }
        }catch(Exception e){
            throw new RuntimeException(e);
        }finally{
        	Env.destroy();
        }
	}

	@Override
	public void after(HttpServletRequest req, HttpServletResponse resp) {
	}

	@Override
	public void destroy() {
	}
	
	
	
	private WebCfg loadConfig(Class<? extends WebCfg> webConfig){
		WebCfg cfg = null;
		try {
			cfg = webConfig.newInstance();
			cfg.init();
		} catch (InstantiationException e) {
			e.printStackTrace();
			throw new ActionException("config instance error.");
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new ActionException("creating config error : IllegalAccessException.");
		}
		return cfg;
	}
}
